<template>
  <div>
    <div v-if="!$route.query.id && (user && user.state!=1)"> <a-button type="primary" @click="toggleEdit">
      {{ isEditing ? '保存' : '编辑' }}
    </a-button>
      <!-- <a-button @click="fillRandomValues" :style="{ marginLeft: '10px' }">
        填充随机数,测试用
      </a-button> -->
      <a-button
        @click="$router.push({ path: '/filelist-view', query: { type: 1, legalCode: user.legalCode } })"
        :style="{ marginLeft: '10px' }"
      >
        扫描件管理
      </a-button>
      <a-button @click="submitApprove" :style="{ marginLeft: '10px' }">
        提交审核
      </a-button></div>

    <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-row :gutter="24" v-if="user">
        <a-col :span="12">
          <a-form-model-item :labelCol="{ span: 10 }" :wrapperCol="{ span: 14 }" label="单位名称">{{
            user.agencyName
          }}</a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item
            :labelCol="{ span: 10 }"
            :wrapperCol="{ span: 14 }"
            label="组织机构代码/统一社会信用代码号"
            >{{ user.legalCode }}</a-form-model-item
          >
        </a-col>
        <a-col :span="field.span || 12" v-for="(field, index) in formFields" :key="field.name">
          <a-form-model-item
            :labelCol="field.labelCol || { span: 10 }"
            :wrapperCol="field.wrapperCol || { span: 14 }"
            v-if="!field.divider"
            :label="field.label"
            :prop="field.name"
          >
            <component
              :is="getComponentType(field.type)"
              v-model="form[field.name]"
              :disabled="field.disabled || !isEditing"
              v-bind="getComponentProps(field)"
            >
              <template v-if="field.type === 'select'" v-for="option in getListOpt(field.options)">
                <a-select-option :key="option.value" :value="option.value">
                  {{ option.label }}
                </a-select-option>
              </template>
            </component>
          </a-form-model-item>
          <a-divider v-else>{{ field.divider }}</a-divider>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="验证码:" prop="checkCode">
            <a-row type="flex" :gutter="8" style="align-items: center">
              <a-col :span="12">
                <a-input v-model="form.checkCode" placeholder="请输入验证码" />
              </a-col>
              <a-col :span="12">
                <div class="captcha-container" @click="refreshCaptcha" style="width:200px;height:50px;">
                  <img :src="captchaUrl" alt="验证码" />
                </div>
              </a-col>
            </a-row>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
  </div>
</template>

<script>
import { formFields } from '../utils/formFields'
import { getRandomValue } from '../utils/randomValueGenerator'
import { mapGetters } from 'vuex'
import { axios } from '@/utils/request'
import { getComponentType } from '../utils/formFields'
import moment from 'moment'
import Vue from 'vue'
export default {
  name: 'BasicInfoForm',
  props: {
    user: {
      type: Object,
    },
  },
  data() {
    return {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      form: {},
      rules: {},
      isEditing: false,
      formFields: formFields,
      sysUserId: null,
      captchaUrl: null,
      opt: {},
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  created() {
    this.refreshCaptcha()
    this.getOptions('sys_platform_code')
  },
  watch: {
    user: {
      handler: function(val) {
        this.initializeForm()
      },
      immediate: true,
    },
  },
  methods: {
    getComponentType,
    getListOpt(url) {
      if (url && typeof url === 'string') {
        return this.opt[url]
      }
      return url
    },
    getOptions(url) {
      if (url && typeof url === 'string') {
        return this.$http.get('/register/common/getDictItems/' + url).then(v => {
          console.log(v)
          this.$set(this.opt,url,v.result.map(item => {
            return {
              ...item,
              value: item.value,
              label: item.text,
            }
          }))

        })
      }
    },
    refreshCaptcha() {
      this.form.checkKey = Math.random()
      this.$http
        .get('/register/common/randomImage/' + this.form.checkKey)
        .then(response => {
          // 可以在此处更新 UI 或执行其他操作
          this.captchaUrl = response.result
        })
        .catch(error => {
          console.error('获取验证码失败:', error)
        })
      // this.captchaUrl = `/api/captcha?t=${new Date().getTime()}`
    },
    initializeForm() {
      this.formFields.forEach(field => {
        if (this.user?.[field.name]?.includes(',')) {
          this.user[field.name] = this.user[field.name].split(',')
        }
        if(field.type==='select' &&  field.mode== 'multiple'&& this.user){
          this.user[field.name] = this.user[field.name] ?? []
        }
        this.$set(this.form, field.name, this.user?.[field.name] || null)
        if (field.rules) {
          this.$set(this.rules, field.name, field.rules)
        }
      })
    },

    getComponentProps(field) {
      if (field.params) {
        return field.params
      }
      switch (field.type) {
        case 'j-area-linkage':
          return { type: 'cascader' }
        case 'date':
          return { format: 'YYYY-MM-DD' }
        case 'select':
          return { mode: field.mode || 'default' }
        case 'upload':
          return {
            name: 'file',
            action: '/upload',
            headers: {
              authorization: 'authorization-text',
            },
            onChange: this.handleUploadChange,
          }
        default:
          return {}
      }
    },
    handleUploadChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        this.$message.success(`${info.file.name} file uploaded successfully`)
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} file upload failed.`)
      }
    },
    submitApprove() {

        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            let formValue = _.cloneDeep(this.form)
            this.formFields.forEach(field => {
              if (field.type === 'date') {
                this.$set(
                  formValue,
                  field.name,
                  formValue[field.name] ? moment(formValue[field.name]).format('YYYY-MM-DD') : '',
                )
              } else if (field.type === 'select' && Array.isArray(formValue[field.name])) {
                this.$set(formValue, field.name, formValue[field.name] ? formValue[field.name].join() : '')
              }
            })
            this.$http
              .post('/register/agencyLegal/submitCheck', { sysUserId: this.user.sysUserId, ...this.user, ...formValue })
              .then(r => {
                this.isEditing = false
                this.$message.success('提交审核成功')
                this.$emit('update', this.form)
              })
          } else {
            this.$message.error('请更正表格中的错误')
          }
        })

    },
    toggleEdit() {
      if (this.isEditing) {
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            let formValue = _.cloneDeep(this.form)
            this.formFields.forEach(field => {
              if (field.type === 'date') {
                this.$set(
                  formValue,
                  field.name,
                  formValue[field.name] ? moment(formValue[field.name]).format('YYYY-MM-DD') : '',
                )
              } else if (field.type === 'select' && Array.isArray(formValue[field.name])) {
                this.$set(formValue, field.name, formValue[field.name] ? formValue[field.name].join() : '')
              }
            })
            this.$http
              .post('/register/agencyLegal/regist', { sysUserId: this.user.sysUserId, ...this.user, ...formValue })
              .then(r => {
                this.isEditing = false
                this.$message.success('提交成功')
                this.$emit('update', this.form)
              })
          } else {
            this.$message.error('请更正表格中的错误')
          }
        })
      } else {
        this.isEditing = true
      }
    },
    fillRandomValues() {
      this.formFields.forEach(field => {
        this.$set(this.form, field.name, getRandomValue(field))
      })
    },
  },
}
</script>
